<script lang="ts">
import { onMounted, ref } from 'vue'
import { type ComponentSize, type TabsPaneContext, type ElAvatar, ElMessageBox, ElMessage } from 'element-plus'
import { Upload, ChatDotRound, UserFilled, ChatLineRound, User, SwitchButton, Edit, Delete, EditPen, CaretBottom } from '@element-plus/icons-vue'
import { communityService, updatePost, deletePost, getPostDetail, getUserPosts } from '@/api/community'
import { useTokenStore } from '@/stores/token'
import router from '@/router'

const pageNum = ref(1)
const pageSize = ref(20)
const total = ref(0)
const activeName = ref('first')
const posts = ref([
    {
        "id": '',
        "content": "",
        "postType": "",
        "likeCount": 0,
        "viewCount": 0,
        "videoUrl": "",
        "coverImg": null,
        "createTime": "",
        "updateTime": "",
        "title": ""
    }
])

export default {
    data() {
        return {
            activeIndex: '',
            searchQuery: '',
            item: '',
            UserFilled,
            User,
            SwitchButton,
            posts,
            Edit,
            Delete,
            EditPen,
            userAvatar: 'https://wpimg.wallstcn.com/f778738c-e4f8-4870-b634-56703b4acafe.gif',
            isDark: false,
            pageNum,
            pageSize,
            total: 30,
            activeName: 'first',
            likeCount: '',
            viewCount: '',
            editDialogVisible: false,
            editingPost: {
                id: '',
                title: '',
                content: '',
                postType: ''
            }
        }
    },
    components: {
        Upload,
        ChatDotRound,
        UserFilled,
        ChatLineRound,
        User,
        SwitchButton,
        EditPen,
        Delete,
        CaretBottom
    },
    methods: {
        async getCommunity() {
            try {
                let result;
                console.log('当前标签页:', this.activeName);
                
                let params = {
                    pageNum: this.pageNum,
                    pageSize: this.pageSize,
                }

                if (this.activeName === 'third') {
                    // 获取当前登录用户的帖子
                    console.log('正在获取我的帖子...');
                    result = await getUserPosts();
                    if (result && result.data) {
                        this.posts = result.data;
                        this.total = this.posts.length;
                    }
                } else if (this.activeName === 'second') {
                    // 获取最热帖子（按点赞量排序）
                    console.log('正在获取最热帖子...');
                    result = await communityService(params);
                    if (result && result.data) {
                        // 确保 posts 是数组
                        const postsArray = Array.isArray(result.data) ? result.data : result.data.records || [];
                        // 对帖子按点赞量进行排序（降序）
                        this.posts = postsArray.sort((a, b) => {
                            // 获取实际的点赞数，如果localStorage中有存储则使用存储的值
                            const likedPosts = JSON.parse(localStorage.getItem('likedPosts')) || {};
                            const aLikes = likedPosts[a.id]?.likeCount || a.likeCount || 0;
                            const bLikes = likedPosts[b.id]?.likeCount || b.likeCount || 0;
                            return bLikes - aLikes;
                        });
                        this.total = this.posts.length;
                        console.log('排序后的帖子:', this.posts); // 添加日志查看排序结果
                    }
                } else {
                    // 获取最新帖子
                    console.log('正在获取最新帖子...');
                    result = await communityService(params);
                    if (result && result.data) {
                        this.posts = result.data;
                        this.total = result.data.total || result.data.length;
                    }
                }
                
                this.loadLikedPosts();
            } catch (error) {
                console.error('获取帖子列表失败:', error);
                ElMessage.error('获取帖子列表失败，请稍后重试');
            }
        },
        
        async getUserPostIds() {
            // 这里需要实现获取用户帖子ID的逻辑
            // 可以通过API获取或其他方式
            return []; // 临时返回空数组
        },

        handleSizeChange(size) {
            this.pageSize = size;
            this.getCommunity();
        },

        handleCurrentChange(page) {
            this.pageNum = page;
            this.getCommunity();
        },

        updateLocalStorage() {
            const likedPosts = this.posts.reduce((acc, post) => {
                acc[post.id] = { likeCount: post.likeCount, viewCount: post.viewCount };
                return acc;
            }, {});
            localStorage.setItem('likedPosts', JSON.stringify(likedPosts));
        },

        loadLikedPosts() {
            const likedPosts = JSON.parse(localStorage.getItem('likedPosts')) || {};
            const favoritePosts = JSON.parse(localStorage.getItem('favoritePosts')) || {};
            this.posts.forEach(post => {
                if (likedPosts[post.id]) {
                    post.likeCount = likedPosts[post.id].likeCount;
                }
                if (favoritePosts[post.id]) {
                    post.viewCount = favoritePosts[post.id].viewCount;
                }
            });
        },

        navigateTologin(page) {
            this.$router.push(`/${page}`);
        },
        navigateToregister(page) {
            this.$router.push(`/${page}`);
        },
        handleLike(postId) {
            const post = this.posts.find(post => post.id === postId);
            if (post) {
                // 获取已存储的点赞数据
                const likedPosts = JSON.parse(localStorage.getItem('likedPosts')) || {};
                
                // 检查是否已经点赞过
                if (likedPosts[postId] && likedPosts[postId].hasLiked) {
                    ElMessage.warning('您已经点赞过这篇帖子了');
                    return;
                }

                // 更新点赞数
                post.likeCount += 1;
                
                // 更新存储数据
                likedPosts[postId] = {
                    likeCount: post.likeCount,
                    viewCount: post.viewCount,
                    hasLiked: true // 标记该帖子已被点赞
                };
                
                // 保存到 localStorage
                localStorage.setItem('likedPosts', JSON.stringify(likedPosts));
                
                console.log(`帖子 ${postId} 被点赞了! 当前点赞数: ${post.likeCount}`);
                ElMessage.success('点赞成功！');

                // 如果当前是最热帖子页面，重新排序
                if (this.activeName === 'second') {
                    this.posts.sort((a, b) => b.likeCount - a.likeCount);
                }
            } else {
                console.log(`没有找到 ID 为 ${postId} 的帖子`);
                ElMessage.error('点赞失败，帖子不存在');
            }
        },
        handlefavorite(postId) {
            const post = this.posts.find(post => post.id === postId);
            if (post) {
                // 获取已存储的收藏数据
                const favoritePosts = JSON.parse(localStorage.getItem('favoritePosts')) || {};
                
                // 检查是否已经收藏过
                if (favoritePosts[postId] && favoritePosts[postId].hasFavorited) {
                    ElMessage.warning('您已经收藏过这篇帖子了');
                    return;
                }

                // 更新收藏数
                post.viewCount = (post.viewCount || 0) + 1;
                
                // 更新存储数据
                favoritePosts[postId] = {
                    viewCount: post.viewCount,
                    hasFavorited: true
                };
                
                // 保存到 localStorage
                localStorage.setItem('favoritePosts', JSON.stringify(favoritePosts));
                
                ElMessage.success('收藏成功！');
            } else {
                ElMessage.error('收藏失败，帖子不存在');
            }
        },
        handlecomment() {
            console.log("评论");
        },
        handlepost() {
            console.log("发布帖子");
        },
        handleCommand(command) {
            if (command === 'logout') {
                ElMessageBox.confirm(
                    '你确认退出登录吗？',
                    '温馨提示',
                    {
                        confirmButtonText: '确认',
                        cancelButtonText: '取消',
                        type: 'warning',
                    }
                )
                    .then(async () => {
                        try {
                            const tokenStore = useTokenStore();
                            tokenStore.removeToken();
                            router.push('/login');
                            localStorage.setItem('isLoggedIn', 'false');
                        } catch (error) {
                            console.error("发生错误：", error);
                        }
                    })
                    .catch(() => {
                        ElMessage({
                            type: 'info',
                            message: '取消退出',
                        });
                    });
            }
        },
        async saveEdit() {
            try {
                if (!this.editingPost.title?.trim()) {
                    ElMessage.error('标题不能为空');
                    return;
                }
                if (!this.editingPost.content?.trim()) {
                    ElMessage.error('内容不能为空');
                    return;
                }
                if (!this.editingPost.postType) {
                    ElMessage.error('请选择帖子类型');
                    return;
                }

                const post = {
                    id: this.editingPost.id,
                    title: this.editingPost.title.trim(),
                    content: this.editingPost.content.trim(),
                    postType: this.editingPost.postType
                };

                await updatePost(post);
                ElMessage.success('更新成功');
                this.editDialogVisible = false;
                await this.getCommunity();
            } catch (error) {
                console.error('更新失败:', error);
                if (error.response) {
                    switch (error.response.status) {
                        case 400:
                            ElMessage.error('请求参数错误：' + (error.response.data?.message || '请检查输入内容'));
                            break;
                        case 401:
                            ElMessage.error('登录已过期，请重新登录');
                            break;
                        case 403:
                            ElMessage.error('您没有权限执行此操作');
                            break;
                        case 404:
                            ElMessage.error('帖子不存在或已被删除');
                            break;
                        case 500:
                            ElMessage.error('服务器错误，请稍后重试');
                            break;
                        default:
                            ElMessage.error('更新失败：' + (error.response.data?.message || '未知错误'));
                    }
                } else if (error.request) {
                    ElMessage.error('网络错误，请检查您的网络连接');
                } else {
                    ElMessage.error('更新失败：' + error.message);
                }
            }
        },
        handleEdit(postId) {
            const post = this.posts.find(p => p.id === postId);
            if (!post) {
                ElMessage.error('帖子不存在');
                return;
            }

            if (this.activeName !== 'third') {
                ElMessage.error('只能编辑自的帖子');
                return;
            }

            this.editingPost = {
                id: post.id,
                title: post.title,
                content: post.content,
                postType: post.postType
            };

            this.editDialogVisible = true;
        },
        async handleDelete(postId) {
            try {
                await ElMessageBox.confirm(
                    '确定要删除这篇帖子吗？',
                    '提示',
                    {
                        confirmButtonText: '确定',
                        cancelButtonText: '取消',
                        type: 'warning'
                    }
                );
                
                const response = await deletePost(postId);
                ElMessage.success('删除成功');
                this.getCommunity();  // 刷新帖子列表
            } catch (error) {
                if (error !== 'cancel') {  // 不是取消操作
                    console.error('错误详情:', {});
                    
                    // 显示具体的错误息
                    const errorMessage = error.response?.data?.message?.replace(/^java\.lang\.Exception: /, '') 
                        || error.message?.replace(/^java\.lang\.Exception: /, '')
                        || '删除失败，请重试';
                    ElMessage.error(errorMessage);
                }
            }
        },
        navigateTo(path) {
            this.$router.push(path);
        },
        async handleClick(tab: TabsPaneContext) {
            console.log('切换到标签页:', tab.props.name); // 修改这里
            this.activeName = tab.props.name; // 修改这里
            this.pageNum = 1;
            await this.getCommunity();
        },
        handleSelect(index: string) {
            console.log('selected:', index);
            // 可以根据需要添加菜单选择的处理逻辑
        },
        handlePostClick(postId) {
            // 导航到帖子详情页面
            this.$router.push(`/community/detail/${postId}`);
        }
    },
    mounted() {
        this.activeName = 'first'; // 确保初始化时设置正确的值
        this.getCommunity();
        this.loadLikedPosts();
    }
}
</script>

<template>
    <el-menu :default-active="activeIndex" class="el-menu-demo" mode="horizontal" :ellipsis="false"
        @select="handleSelect" style="height:75px;box-shadow: 0 2px 4px rgba(0,0,0,0.1);">
        <el-menu-item index="0">
            <img style="width: 100px;height: 70px;margin-left: 53px;margin-right: 10px;" src="@/assets/logo.jpg"
                alt="CodeCash" />
        </el-menu-item>
        <el-search-item index="1" style="transform: translate(-90%,15px);">
            <el-input v-model="searchQuery" style="width: 300px;height:40px;" placeholder="搜索您感兴趣的内容" clearable />
            <el-button type="search" style="height: 40px;width: 80px;background-color:#007bff;color:white;">搜索</el-button>
        </el-search-item>
        <el-router-menu index="2" style="transform: translateX(-2%);">
            <el-link href="/" style="color: black; font-size: 18px;padding: 20px;">首页</el-link>
            <el-link href="/programmer" style="color: black; font-size: 18px;padding: 20px;">程序员</el-link>
            <el-link href="/task" style="color: black; font-size: 18px;padding: 20px;">任务大厅</el-link>
            <el-link href="/community" style="color: black; font-size: 18px;padding: 20px;">社区</el-link>
            <el-link href="/user/call" style="color: black; font-size: 18px;padding: 20px;">联系我们</el-link>
        </el-router-menu>
        <el-buttons-item index="3" style="transform: translateY(25%);margin-right: 20px;">
            <el-dropdown placement="bottom-end">
                <el-avatar :src="userAvatar" size="medium" />
                <el-icon>
                    <CaretBottom />
                </el-icon>
                <template #dropdown>
                    <el-dropdown-menu>
                        <el-dropdown-item command="userInfo" :icon="User"
                            @click="navigateTo('/userInfo')">个人中心</el-dropdown-item>
                        <el-dropdown-item command="logout" :icon="SwitchButton"
                            @click="handleCommand('logout')">退出登录</el-dropdown-item>
                    </el-dropdown-menu>
                </template>
            </el-dropdown>
        </el-buttons-item>
    </el-menu>
    <el-main>
        <div class="head">
            <img src="../assets/logo_xc.png">
            <div>
                <ul>
                    <h2>欢迎来到我们的社区页面！<el-icon :size="40" style="padding: 5px">
                            <ChatDotRound />
                        </el-icon></h2>
                    <li style="font-size: 16px;padding: 5px;">这是一个充满活力的交流平台</li>
                    <li style="font-size: 16px;padding: 5px;margin-right: 200px;">
                        您可以在这里自由地发布或分享丰富多彩的内容，包括引人入胜的文字、生动有趣的图片以及精彩绝伦的视频。</li>
                    <el-button type="primary" style="margin-left: 150px;margin-top: 50px;"
                        @click="navigateTo('/community/post')">
                        发布帖子<el-icon class="el-icon--right">
                            <Upload />
                        </el-icon>
                    </el-button>
                </ul>
            </div>
        </div>
        <el-tabs v-model="activeName" class="demo-tabs" @tab-click="handleClick"
            style="margin-left: 280px;margin-right: 200px;">
            <el-tab-pane label="最新发布" name="first"></el-tab-pane>
            <el-tab-pane label="最热帖子" name="second"></el-tab-pane>
            <el-tab-pane label="我的帖子" name="third"></el-tab-pane>
        </el-tabs>
        <div class="box-card" v-for="post in posts" :key="post.id" @click="handlePostClick(post.id)">
            <div class="card-header">
                <div class="user-info">
                    <el-avatar :src="userAvatar" :size="50" />
                    <div class="post-meta">
                        <p class="post-type">帖子类型：{{ post.postType }}</p>
                        <p class="post-time">发布时间：{{ post.createTime }}</p>
                    </div>
                </div>
                <template v-if="activeName === 'third'">
                    <div class="action-buttons">
                        <el-button 
                            type="primary" 
                            size="small" 
                            @click.stop="handleEdit(post.id)"
                        >
                            <el-icon><EditPen /></el-icon>编辑
                        </el-button>
                        <el-button 
                            type="danger" 
                            size="small" 
                            @click.stop="handleDelete(post.id)"
                        >
                            <el-icon><Delete /></el-icon>删除
                        </el-button>
                    </div>
                </template>
            </div>

            <div class="card-body">
                <h3 class="post-title">{{ post.title }}</h3>
                <p class="post-content">{{ post.content }}</p>
            </div>

            <div class="card-footer" @click.stop>
                <template v-if="activeName !== 'third'">
                    <div class="interaction-item" @click="handleLike(post.id)">
                        <img src="../assets/like.png" alt="点赞">
                        <span>{{ post.likeCount }}</span>
                    </div>
                    <div class="interaction-item" @click="handlefavorite(post.id)">
                        <img src="../assets/favorite.png" alt="收藏">
                        <span>{{ post.viewCount }}</span>
                    </div>
                    <div class="interaction-item" @click="handlecomment">
                        <img src="../assets/comment.png" alt="评论" @click="navigateTo('/community/detail/' + post.id)">
                        <span>评论</span>
                    </div>
                </template>
            </div>
        </div>
        <el-pagination
            style="margin-left: 500px;color: #2994F2;justify-content: center;align-items: center;margin: 40px auto;"
            v-model:current-page="pageNum" v-model:page-size="pageSize" :page-sizes="[5, 10, 15, 20]" :total="total"
            layout="total, sizes, prev, pager, next, jumper" @size-change="handleSizeChange"
            @current-change="handleCurrentChange" />
    </el-main>

    <!-- 编辑弹窗 -->
    <el-dialog v-model="editDialogVisible" title="编辑帖子" width="50%" :close-on-click-modal="false">
        <el-form :model="editingPost" label-width="80px">
            <el-form-item label="标题">
                <el-input v-model="editingPost.title" placeholder="请输入标题" />
            </el-form-item>
            <el-form-item label="类型">
                <el-select v-model="editingPost.postType" placeholder="请选择帖子类型">
                    <el-option label="programmer" value="programmer" />
                    <el-option label="task" value="task" />
                    <el-option label="community" value="community" />
                </el-select>
            </el-form-item>
            <el-form-item label="内容">
                <el-input 
                    v-model="editingPost.content" 
                    type="textarea" 
                    :rows="6" 
                    placeholder="请输入内容" 
                />
            </el-form-item>
        </el-form>
        <template #footer>
            <span class="dialog-footer">
                <el-button @click="editDialogVisible = false">取消</el-button>
                <el-button type="primary" @click="saveEdit">确定</el-button>
            </span>
        </template>
    </el-dialog>

    <el-footer>
        <div class="footer">
            <div>
                <a href="#">动态公告</a> |
                <a href="#">帮助</a> |
                <a href="#">关我们</a> |
                <a href="#">合作伙伴</a> |
                <a href="#">意见反</a> |
                <text style="color: rgb(78, 77, 77);">@"码上有钱"程序员接单台</text>
            </div>
            <div class="credits">
                粤ICP备20220901号-4 | 粤公网安备33011002011599号
            </div>
        </div>
    </el-footer>
</template>

<style scoped>
/* 保持原有样式不变 */
.el-menu--horizontal>.el-menu-item:nth-child(1) {
    margin-right: auto;
}

.head {
    display: flex;
    align-items: center;
    justify-content: center;
    margin: auto;
}

.head div {
    margin-top: -10px;
    flex-direction: column;
}

.head ul {
    margin-left: 100px;
}

.head img {
    width: 480px;
    height: 360px;
    margin-left: 280px;
    padding: 20px;
}

.demo-tabs>.el-tabs__content {
    padding: 32px;
    color: #6b778c;
    font-size: 36px;
    font-weight: 600;
    margin: auto;
}

.box-card {
    background: white;
    border-radius: 12px;
    box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
    padding: 20px;
    margin: 20px auto;
    width: 80%;
    max-width: 1000px;
    min-width: 300px;
    position: relative;
    transition: all 0.3s ease;
    overflow-wrap: break-word;
    word-wrap: break-word;
    cursor: pointer;
}

.box-card:hover {
    transform: translateY(-2px);
    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
}

.card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20px;
}

.user-info {
    display: flex;
    align-items: center;
    gap: 15px;
}

.post-meta {
    display: flex;
    flex-direction: column;
    gap: 5px;
}

.post-type {
    color: #2994F2;
    font-size: 14px;
    margin: 0;
}

.post-time {
    color: #999;
    font-size: 12px;
    margin: 0;
}

.card-body {
    padding: 0 10px;
    width: 100%;
    box-sizing: border-box;
}

.post-title {
    font-size: 18px;
    font-weight: 600;
    color: #333;
    margin-bottom: 12px;
    word-break: break-word;
    overflow-wrap: break-word;
}

.post-content {
    font-size: 14px;
    color: #666;
    line-height: 1.6;
    margin-bottom: 20px;
    white-space: pre-wrap;
    word-break: break-word;
    overflow-wrap: break-word;
    max-width: 100%;
}

.card-footer {
    display: flex;
    justify-content: flex-end;
    gap: 20px;
    padding-top: 15px;
    border-top: 1px solid #eee;
}

.interaction-item {
    display: flex;
    align-items: center;
    gap: 5px;
    cursor: pointer;
    transition: all 0.2s ease;
}

.interaction-item:hover {
    color: #2994F2;
}

.interaction-item img {
    width: 20px;
    height: 20px;
}

.interaction-item span {
    font-size: 14px;
    color: #666;
}

.footer {
    padding: 10px 0;
    border-top: 1px solid #ddd;
    text-align: center;
}

.footer a {
    text-decoration: none;
    color: rgb(78, 77, 77);
    background: transparent;
    border: none;
    cursor: pointer;
}

.footer .credits {
    margin-top: 5px;
    font-size: 12px;
    color: gray;
}

/* 弹窗相关样式 */
.dialog-footer {
    display: flex;
    justify-content: flex-end;
    gap: 10px;
}

:deep(.el-dialog) {
    border-radius: 8px;
}

:deep(.el-dialog__header) {
    margin-right: 0;
    border-bottom: 1px solid #eee;
    padding: 20px;
}

:deep(.el-dialog__body) {
    padding: 30px 20px;
}

:deep(.el-dialog__footer) {
    border-top: 1px solid #eee;
    padding: 20px;
}

:deep(.el-form-item__label) {
    font-weight: 500;
}

:deep(.el-input__inner) {
    border-radius: 4px;
}

:deep(.el-textarea__inner) {
    border-radius: 4px;
}

/* 添加响应式布局 */
@media screen and (max-width: 768px) {
    .box-card {
        width: 95%;
        padding: 15px;
    }

    .card-header {
        flex-direction: column;
        align-items: flex-start;
    }

    .action-buttons {
        margin-top: 10px;
        width: 100%;
        display: flex;
        justify-content: flex-end;
    }

    .card-footer {
        flex-wrap: wrap;
        justify-content: space-around;
    }
}
</style>